<template>

  <el-form v-if="!contractData?.disabled" :inline="true" :model="queryParams" label-position="right" size="small"
    class="filter-form-inline">
    <el-row :gutter="40" style="margin-left: 0px; margin-right: 0px">
      <el-col :span="6">
        <el-form-item label="合同类型" style="width: 100%">
          <el-select v-model="queryParams.contractType" style="width: 100%" placeholder="请选择合同类型">
            <el-option v-for="item in contractTypeData" :key="item.id" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="合同类对象" style="width: 100%">
          <el-select v-model="queryParams.contractObjectType" style="width: 100%" placeholder="请选择合同对象">
            <el-option v-for="item in contractObjectTypeData" :key="item.id" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="10">
        <el-form-item style="width: 100%">
          <more-search-btn v-model:is-more="visible" />
          <el-button class="border-btn" @click="handlReset">重置</el-button>
          <el-button type="primary" class="main-btn" @click="handlSearch">搜索</el-button>
        </el-form-item>
      </el-col>

    </el-row>
    <el-row :gutter="40" style="margin-left: 0px; margin-right: 0px">
      <template v-if="visible">
        <el-col :span="6">
          <el-form-item label="创建时间" style="width: 100%">
            <date-range-picker v-model:date="date" style="width: 100%" type="daterange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" @change="handlDate" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="结束时间" style="width: 100%">
            <date-range-picker v-model:date="date1" style="width: 100%" type="daterange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" @change="handlDate1" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="负责人" style="width: 100%">
            <el-select v-model="queryParams.contractHeadId" style="width: 100%" placeholder="请选择负责人"
              @change="handlChangeHead">
              <el-option v-for="item in headList" :key="item.id" :label="item.realName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="关键字" style="width: 100%">
            <el-input v-model="queryParams.keyWord" placeholder="名称，编号，对象名称" />
          </el-form-item>
        </el-col>
      </template>
    </el-row>
    <el-row :gutter="40" style="margin-left: 0px; margin-right: 0px">
      <el-col>
        <el-button v-auth="{v: contractData.pms}" type="primary" size="small" style="margin-bottom: 20px;"
          @click="handlAdd">新建合同
        </el-button>
      </el-col>
    </el-row>

  </el-form>

  <div v-else style="display: flex; justify-content: space-between">
    <div style="width: 50%">
      <el-button v-if="isOperation" class="border-btn" size="small" style="margin-bottom: 20px;" @click="handlAdd">新建合同
      </el-button>
    </div>
    <el-form :model="queryParams" label-position="right" size="small" class="filter-form-inline"
      style="width: 50%;display: flex;justify-content: flex-end;">
      <el-row :gutter="40" style="margin-left: 0px; margin-right: 0px">
        <el-form-item label="关键字">
          <el-input v-model="queryParams.keyWord" placeholder="名称，编号，对象名称" />
        </el-form-item>
        <el-form-item style="margin-left: 20px">
          <filter-popover right="20px" :form-list="formList" @onConfirm="filterDataConfirm" @onReset="handlReset" />
        </el-form-item>
      </el-row>
    </el-form>
  </div>

  <table-view :data="tableData" header-cell-class-name="table-header" size="medium" border :cell-style="cellStyle"
    @row-click="aloneClick">
    <el-table-column prop="contractNumber" label="合同编号" :min-width="120" header-align="center" />

    <el-table-column prop="contractName" label="合同名称" :min-width="160" header-align="center"
      :show-overflow-tooltip="true" />

    <el-table-column prop="address" label="合同类型" v-if="tableColumn" :min-width="120" align="center">
      <template #default="{row}">
        {{ getLabel('contract_type', row.contractType) }}
      </template>
    </el-table-column>

    <el-table-column label="合同对象" v-if="tableColumn" :min-width="120" align="center">
      <template #default="{row}">
        {{ getLabel('contract_object', row.contractObjectType) }}
      </template>
    </el-table-column>

    <el-table-column show-overflow-tooltip prop="objectName" v-if="tableColumn" label="相对方名称" :min-width="140"
      header-align="center" />

    <el-table-column prop="contractBeginTime" label="开始日期" :min-width="120" align="center">
      <template #default="{row}">
        {{ dateFormat("yyyy-mm-dd",row.contractBeginTime) }}
      </template>
    </el-table-column>

    <el-table-column prop="contractEndTime" label="结束日期" :min-width="120" align="center">
      <template #default="{row}">
        {{ dateFormat("yyyy-mm-dd",row.contractEndTime) }}
      </template>
    </el-table-column>

    <el-table-column prop="contractHeadName" label="合同负责人" :min-width="120" align="center" />

    <el-table-column prop="contractDepartmentName" label="归属部门" :min-width="150" header-align="center"
      :show-overflow-tooltip="true" />

    <el-table-column prop="createdAt" label="创建时间" align="center" :min-width="180" header-align="center">
      <template #default="{row}">
        {{ dateFormat("yyyy-mm-dd HH:MM:SS",row.createdAt) }}
      </template>
    </el-table-column>
    <el-table-column prop="address" label="状态" align="center" :min-width="120">
      <template #default="{row}">
        <div style="line-height:20px">
          {{ getLabel('contract_status', row.contractStatus) }}
        </div>
        <div style="line-height: 20px" class="flow-status-color" v-if="row.flowStatus == 'REJECT_INITIATOR'">
          [驳回]
        </div>
      </template>
    </el-table-column>
    <el-table-column v-if="isOperation" label="操作" align="center" :min-width="120" fixed="right">
      <template #default="{row}">
        <template
          v-if="row.contractStatus === '-4' || row.contractStatus === '-3' || row.contractStatus === '-1' || row.flowStatus == 'REJECT_INITIATOR'  ">
          <el-button v-auth="{v: contractData.pms}" type="text" @click="handlEdit(row)">编辑
          </el-button>
        </template>
        <template v-if="row.contractStatus === '-1' || row.contractStatus === '-3'  ">
          <el-button v-auth="{v: contractData.pms}" type="text" @click="handlDele(row.id,1)">删除
          </el-button>
        </template>
        <el-button v-auth="{v: contractData.pms, bool: row.contractStatus == 1}" type="text"
          @click="handlEnd(row.id,1)">履约结束
        </el-button>
      </template>
    </el-table-column>
  </table-view>
  <Pagination v-model:page="queryParams.page" v-model:limit="queryParams.pageSize"
    style="display: flex; justify-content: flex-end" :total="total" @pagination="handlList" />

  <!--新建合同-->
  <addContract ref="addContractDialog" :disabled="contractData?.disabled" @succsess="succsess" />
  <!--合同详情-->
  <detail-drawer ref="detailDrawer" custom-title :size-width="1000">
    <template #title>
      <div style="display: flex;justify-content: space-between;align-items: center">
        <div style="width: 40%">
          <span style="margin-right: 15px">{{ contractList?.contractName }} </span>
          <el-tag type="warning" size="small" style="margin-right: 15px">
            {{ getLabel('contract_status', contractList?.contractStatus) }}
          </el-tag>
          <el-tag type="warning" size="small" style="margin-right: 15px" v-if="contractList?.flowStatus == 'REJECT_INITIATOR'">
           驳回
          </el-tag>
        </div>
        <div style="width: 60%;text-align: right">
          <template
            v-if="contractList?.contractStatus === '-4' || contractLis?.contractStatus === '-3' ||
             contractList?.contractStatus === '-1' || contractList?.flowStatus == 'REJECT_INITIATOR'">
            <el-button type="primary" size="mini" @click="handlEdit(contractList)">编辑
            </el-button>
          </template>
          <template v-if=" contractList?.contractStatus === '-3' || contractList?.contractStatus === '-1'">
            <el-button type="primary" size="mini" @click="handlDele(contractList?.id,2)">删除
            </el-button>
          </template>
          <el-button v-if="contractList?.contractStatus == 1" type="primary" size="mini"
            @click="handlEnd(contractList.id,2)">履约结束
          </el-button>
        </div>
      </div>

    </template>
    <template v-if="contractId !== 0" #contents>
      <div class="drawer-content">
        <div class="history-list">
          <contract-detail ref="salesDetailDrawer" :contract-id="contractId" />
        </div>
      </div>
    </template>
  </detail-drawer>

</template>

<script>
import {
  defineAsyncComponent,
  getCurrentInstance,
  inject,
  onMounted,
  reactive,
  toRefs,
} from "vue";
import { useRoute, useRouter } from "vue-router";
import { crmStore } from "@CRM/store";

export default {
  name: "Contract",
  components: {
    addContract: defineAsyncComponent(() => import("./addContract.vue")),
    contractDetail: defineAsyncComponent(() => import("./contractDetail.vue")),
  },
  props: {
    contractData: {
      type: Object,
      default() {
        return {};
      },
    },
    contractParams: {
      type: Object,
      default() {
        return null;
      },
    },
    booleId: {
      type: Boolean,
      default: false,
    },
    isOperation: {
      type: Boolean,
      default: true,
    },
    tableColumn: {
      type: Boolean,
      default: true,
    },
  },
  setup(props, context) {
    const route = useRoute();
    const router = useRouter();
    const currentInstance = getCurrentInstance();
    const api = inject("api");
    var data = reactive({
      tableData: [],
      total: 0,
      addContractDialog: null,
      salesDetailDrawer: null,
      detailDrawer: null,
      queryParams: {
        objectId: Number(route.query.id),
        contractObjectType: props.contractData?.contractObjectType,
        contractType: props.contractData?.contractType,
        keyWord: "",
        contractHeadId: "",
        contractEndTimeStart: null,
        contractEndTimeEnd: null,
        startTime: null,
        endTime: null,
        pageSize: 20,
        page: 1,
      },
      contractId: 0,
      contractList: null,
      contractTypeData:
        crmStore.getters["dictionary/getDictionary"]["contract_type"],
      contractObjectTypeData:
        crmStore.getters["dictionary/getDictionary"]["contract_object"],
      headList: [],
      date: "",
      date1: "",
      visible: false,
      formList: [
        {
          key: "contractHeadId",
          label: "负责人",
          form_type: "select",
          value: "",
          is_search: false,
          options: [],
          setting: {
            label: "realName",
            value: "id",
          },
        },
        {
          key: "date_range1",
          label: "创建时间",
          form_type: "daterange",
          value: [],
          is_search: false,
          options: [],
        },
        {
          key: "date_range2",
          label: "结束时间",
          form_type: "daterange",
          value: [],
          is_search: false,
          options: [],
        },
      ],
    });

    // 获取负责人
    const handlHead = () => {
      api.terminal.HEAD_PEOPLE(1).then((res) => {
        if (res.code === 0) {
          data.headList = res.data;
          data.formList[0].options = res.data;
        }
      });
    };

    const handlDate = (val) => {
      if (val) {
        data.queryParams.startTime = val[0];
        data.queryParams.endTime = val[1];
      }
    };

    const handlDate1 = (val) => {
      if (val) {
        data.queryParams.contractEndTimeStart = val[0];
        data.queryParams.contractEndTimeEnd = val[1];
      }
    };

    const handlAdd = () => {
      data.addContractDialog.open(props.contractData, null, props.booleId);
    };

    const handlSearch = () => {
      data.queryParams.page = 1;
      handlList();
    };

    const filterDataConfirm = (val) => {
      data.queryParams.page = 1;
      data.queryParams.contractHeadId = val.contractHeadId;
      data.queryParams.contractEndTimeStart = val.date_range2[0];
      data.queryParams.contractEndTimeEnd = val.date_range2[1];
      data.queryParams.startTime = val.date_range1[0];
      data.queryParams.endTime = val.date_range1[1];
      handlList();
    };

    const handlReset = () => {
      data.queryParams = {
        objectId: Number(route.query.id),
        contractObjectType: props.contractData?.contractObjectType,
        contractType: props.contractData?.contractType,
        keyWord: "",
        contractHeadId: "",
        contractEndTimeStart: null,
        contractEndTimeEnd: null,
        startTime: null,
        endTime: null,
        pageSize: 20,
        page: 1,
      };
      data.date = "";
      data.date1 = "";
      handlList();
    };

    // 获取列表
    const handlList = () => {
      api.terminal.SALES_LIST(data.queryParams).then((res) => {
        if (res.code === 0) {
          data.tableData = res.data.list || [];
          data.total = res.data.total;
        }
      });
    };

    // 编辑
    const handlEdit = (row) => {
      data.addContractDialog.open(props.contractData, row, props.booleId);
    };

    // 删除
    const handlDele = (id, num) => {
      currentInstance.proxy
        .alertBox({
          message: "删除数据后不可恢复,确定删除？",
        })
        .then(() => {
          api.terminal.SALES_DELETE(id).then((res) => {
            if (res.code === 0) {
              currentInstance.proxy.customMessage({
                type: "success",
                message: "删除成功",
              });
              if (num === 1) {
                handlList();
              } else {
                data.detailDrawer.close();
              }
            } else {
              currentInstance.proxy.customMessage({
                type: "error",
                message: res.msg,
              });
            }
          });
        })
        .catch((err) => {
          console.log(err);
        });
    };

    // 终止
    const handlEnd = (id, num) => {
      currentInstance.proxy
        .alertBox({
          message: "更改状态后不可撤销，确认更改合同状态为履约结束",
          title: "履约结束",
        })
        .then(() => {
          api.terminal.SALES_END(id).then((res) => {
            if (res.code === 0) {
              if (num === 1) {
                handlList();
              } else {
                data.salesDetailDrawer.handlDetail(data.contractId);
              }
            } else {
              currentInstance.proxy.customMessage({
                type: "error",
                message: res.msg,
              });
            }
          });
        })
        .catch((err) => {
          console.log(err);
        });
    };

    // 刷新列表
    const succsess = () => {
      handlList();
    };

    const aloneClick = (row, column) => {
      if (column.label === "操作") return;
      data.contractId = row.id;
      data.contractList = row;
      data.detailDrawer.open();
    };

    const cellStyle = () => {
      return "cursor:pointer;";
    };
    onMounted(() => {
      handlList();
      handlHead();
    });

    return {
      ...toRefs(data),
      handlAdd,
      handlList,
      handlEdit,
      handlDele,
      aloneClick,
      cellStyle,
      succsess,
      handlEnd,
      handlHead,
      handlDate,
      handlDate1,
      handlReset,
      handlSearch,
      filterDataConfirm,
    };
  },
};
</script>

<style lang="scss" scoped>
:deep(.el-button--text) {
  padding: 0;
  border: 0;
}
</style>
